<template>
    <div class="page-container">
        <el-page-header @back="goBack" content="创建新交易订单"></el-page-header>

        <el-card class="mt-4">
            <el-form :model="form" ref="orderFormRef" :rules="rules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户ID" prop="userId">
                            <el-input v-model.number="form.userId" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="交易类型" prop="type">
                            <el-select v-model="form.type" placeholder="选择交易类型" style="width: 100%;">
                                <el-option label="买入" value="BUY"></el-option>
                                <el-option label="卖出" value="SELL"></el-option>
                                <el-option label="再平衡" value="REBALANCE"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="账户ID" prop="accountId">
                            <el-input-number v-model="form.accountId" :min="1" controls-position="right"
                                style="width: 100%;"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组合产品ID" prop="productId">
                            <el-input-number v-model="form.productId" :min="1" controls-position="right"
                                style="width: 100%;"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="订单总额">
                            <el-input :value="totalAmount.toFixed(2)" disabled>
                                <template #prepend>¥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-divider>订单明细</el-divider>

                <div v-for="(detail, index) in form.details" :key="index" class="detail-item">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item :label="'基金代码 ' + (index + 1)" :prop="'details.' + index + '.fundCode'"
                                :rules="rules.fundCode">
                                <el-input v-model="detail.fundCode" placeholder="输入基金代码"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label-width="0" :prop="'details.' + index + '.amount'"
                                :rules="rules.detailAmount">
                                <el-input-number v-model="detail.amount" :precision="2" :step="100" :min="0"
                                    placeholder="交易金额" style="width: 100%;"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label-width="0" :prop="'details.' + index + '.direction'"
                                :rules="rules.direction">
                                <el-select v-model="detail.direction" placeholder="买卖方向" style="width: 100%;">
                                    <el-option label="买入" value="BUY"></el-option>
                                    <el-option label="卖出" value="SELL"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <el-button @click.prevent="removeDetail(index)" type="danger" circle plain
                                :icon="Delete"></el-button>
                        </el-col>
                    </el-row>
                </div>

                <el-form-item>
                    <el-button @click="addDetail" type="primary" plain>添加一项</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting">提交订单</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Delete } from '@element-plus/icons-vue';
import axios from 'axios';
import { useAuthStore } from '@/store/auth';

const router = useRouter();
const authStore = useAuthStore();
const orderFormRef = ref(null);
const submitting = ref(false);

const form = reactive({
    userId: authStore.state.user?.id,
    accountId: null,
    productId: null,
    type: '',
    amount: 0,
    details: [
        { fundCode: '', amount: null, direction: '' }
    ]
});

const rules = {
    accountId: [{ required: true, message: '账户ID不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '组合产品ID不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
    fundCode: [{ required: true, message: '基金代码不能为空', trigger: 'blur' }],
    detailAmount: [{ required: true, message: '交易金额不能为空', trigger: 'blur' }],
    direction: [{ required: true, message: '请选择买卖方向', trigger: 'change' }],
};

const totalAmount = computed(() => {
    return form.details.reduce((sum, detail) => sum + (Number(detail.amount) || 0), 0);
});

const addDetail = () => {
    form.details.push({ fundCode: '', amount: null, direction: '' });
};

const removeDetail = (index) => {
    form.details.splice(index, 1);
};

const goBack = () => {
    router.back();
};

const submitForm = async () => {
    if (!orderFormRef.value) return;
    await orderFormRef.value.validate(async (valid) => {
        if (valid) {
            if (form.details.length === 0) {
                ElMessage.warning('请至少添加一项订单明细。');
                return;
            }

            submitting.value = true;
            form.amount = totalAmount.value; // 更新主订单总额

            try {
                // API 调用在 tradeApi 中已定义，这里直接使用 axios
                const response = await axios.post('/api/trade/order', form);
                ElMessage.success('订单创建成功！');
                // 跳转到新订单的详情页
                router.push({ name: 'TradeOrderDetail', params: { id: response.data.id } });
            } catch (error) {
                ElMessage.error('订单创建失败: ' + (error.response?.data?.message || error.message));
            } finally {
                submitting.value = false;
            }
        } else {
            ElMessage.error('请检查表单中的必填项。');
        }
    });
};
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}

.detail-item {
    padding: 10px 15px 0 15px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    margin-bottom: 15px;
}
</style>